package com.young.core.dao.impl;

import com.young.common.query.Pagination;
import com.young.common.query.PaginationBuilder;
import com.young.common.query.Query;
import com.young.core.dao.BaseDao;
import com.young.core.dao.TraceDao;
import com.young.core.domain.TraceDO;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class TraceDaoImpl extends BaseDao implements TraceDao {
    
    @Override
    public void insert(TraceDO trace) {
        this.sqlSession.insert("TraceMapper.insert", trace);
    }

    @Override
    public int update(TraceDO trace) {
        return this.sqlSession.update("TraceMapper.update", trace);
    }

    @Override
    public Pagination<TraceDO> query(Query query) {
        Map<String, Object> parameters = query.buildParameters();
        int amount = amount(parameters);
        PaginationBuilder<TraceDO> builder = PaginationBuilder.query(query);
        builder.amount(amount);
        if (amount > 0) {
            List<TraceDO> list = this.sqlSession.selectList("TraceMapper.query", parameters);
            builder.result(list);
        } else {
            builder.result(new ArrayList<>());
        }
        return builder.build();
    }

    @Override
    public TraceDO get(String traceId) {
        return this.sqlSession.selectOne("TraceMapper.getByTraceId", traceId);
    }


    @Override
    public int deleteExpired(Date time,Collection<String> excludes) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("time", time);
        parameters.put("excludes",excludes);
        return this.sqlSession.delete("TraceMapper.deleteExpired", parameters);
    }

    private int amount(Map<String, Object> parameters) {
        return this.sqlSession.selectOne("TraceMapper.getAmount", parameters);
    }

}
